package com.wrial.seckill.service.impl;
/*
 * @Author  Wrial
 * @Date Created in 15:56 2020/4/5
 * @Description
 */

import com.wrial.seckill.dao.ItemDOMapper;
import com.wrial.seckill.dao.ItemStockDOMapper;
import com.wrial.seckill.dataobject.ItemDO;
import com.wrial.seckill.dataobject.ItemStockDO;
import com.wrial.seckill.error.CustomizeErrorCode;
import com.wrial.seckill.error.CustomizeException;
import com.wrial.seckill.service.ItemService;
import com.wrial.seckill.service.PromoService;
import com.wrial.seckill.service.model.ItemModel;
import com.wrial.seckill.service.model.PromoModel;
import com.wrial.seckill.validator.ValidationResult;
import com.wrial.seckill.validator.ValidatorImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
@CrossOrigin(origins = {"*"}, allowCredentials = "true")
// 校验入参(在Model里)  转化model为dataObject  写入数据库  返回对象
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ValidatorImpl validator;
    @Autowired
    private ItemDOMapper itemDOMapper;
    @Autowired
    private ItemStockDOMapper itemStockDOMapper;
    @Autowired
    private PromoService promoService;

    @Override
    @Transactional
    public ItemModel createItem(ItemModel model) {

        ValidationResult validate = validator.validate(model);
        if (validate.isHasErrors()) {
            throw new CustomizeException(CustomizeErrorCode.PARAMETER_VALIDATION_ERROR.setMessage(validate.getErrMsg()));
        }

        //转化itemmodel->dataobject
        ItemDO itemDO = this.convertItemDOFromItemModel(model);

        //写入数据库
        itemDOMapper.insert(itemDO);
        model.setId(itemDO.getId());

        ItemStockDO itemStockDO = this.convertItemStockDOFromItemModel(model);

        itemStockDOMapper.insert(itemStockDO);

        //返回创建完成的对象（通过查询数据库）
        return this.getItemById(model.getId());
    }

    @Override
    public List<ItemModel> listItem() {
        List<ItemDO> itemDOList = itemDOMapper.selectAll();
        List<ItemModel> itemModelList = itemDOList.stream().map(itemDO -> {
            ItemStockDO itemStockDO = itemStockDOMapper.getItemStockByItemId(itemDO.getId());
            ItemModel itemModel = this.convertModelFromDataObject(itemDO, itemStockDO);
            return itemModel;
        }).collect(Collectors.toList());
        return itemModelList;
    }

    @Override
    public ItemModel getItemById(Integer id) {
        // 查询商品
        ItemDO itemDO = itemDOMapper.selectById(id);
        if (itemDO == null) return null;
        // 查询stock
        ItemStockDO stockDO = itemStockDOMapper.getItemStockByItemId(id);
        if (stockDO == null) return null;
        ItemModel itemModel = convertModelFromDataObject(itemDO, stockDO);
        //获取活动商品信息秒杀信息
        PromoModel promoModel = promoService.getPromoByItemId(itemModel.getId());
        if(promoModel != null && promoModel.getStatus().intValue() != 3){
            itemModel.setPromoModel(promoModel);
        }
        return itemModel;
    }

    @Override
    @Transactional
    public boolean decreaseStock(Integer itemId, Integer amount) {
        int affectRow = itemStockDOMapper.decreaseStock(itemId, amount);
        if (affectRow > 0) {
            // 成功
            return true;
        } else {
            // 失败
            return false;
        }
    }

    @Override
    public void increaseSales(Integer itemId, Integer amount) {
        itemDOMapper.increaseSales(itemId,amount);

    }

    private ItemModel convertModelFromDataObject(ItemDO itemDO, ItemStockDO itemStockDO) {
        ItemModel itemModel = new ItemModel();
        BeanUtils.copyProperties(itemDO, itemModel);
        // 尽量避免使用double，因为精度不好控制，前端处理起来比较麻烦
        itemModel.setPrice(new BigDecimal(itemDO.getPrice()));
        itemModel.setStock(itemStockDO.getStock());
        return itemModel;
    }

    private ItemDO convertItemDOFromItemModel(ItemModel itemModel) {
        if (itemModel == null) {
            return null;
        }
        ItemDO itemDO = new ItemDO();
        BeanUtils.copyProperties(itemModel, itemDO);
        // 将double的值设置进去
        itemDO.setPrice(itemModel.getPrice().doubleValue());
        return itemDO;
    }

    private ItemStockDO convertItemStockDOFromItemModel(ItemModel itemModel) {
        if (itemModel == null) {
            return null;
        }
        ItemStockDO itemStockDO = new ItemStockDO();
        itemStockDO.setItemId(itemModel.getId());
        itemStockDO.setStock(itemModel.getStock());
        return itemStockDO;
    }
}
